import {
  ajax
} from "../../utils/request.js";

const queryOpenId = (data) => {
  return ajax('/api/user/getphone', "POST", data)
}
const getPhoneNumber = (data) => {
  return ajax('/api/user/getphonenumber', "POST", data)
}


// 服务端接口 - 获取openid
function queryOpenIdFn(code) {
  console.log("code", code);
  return new Promise(resolve => {
    queryOpenId({
        code
      }).then(res => {
        console.log(res.data);
        // if (res.data !== 0) {
        // 	console.log('获取openid失败1：', res.msg);
        // 	return
        // }
        // uni.setStorageSync('openId', res.content.openid)
        uni.setStorageSync('openId', res.data)
        resolve(res.data)
      })
      .catch(err => {
        console.log('获取openid失败2：', err);
      })
  })
}

// 服务端接口 - 获取手机号
function getPhoneNumberFn(phoneCode, openId) {
  console.log("phoneCode", phoneCode);
  console.log("openId", openId);
  return new Promise(resolve => {
    getPhoneNumber({
        code: phoneCode,
        openId: openId,
      }).then(res => {
        // if (res.code !== 0) {
        // 	console.log('获取手机号失败1：', res.msg);
        // 	return
        // }

        console.log('获取手机号成功：', res.data);
        resolve(res)
      })
      .catch(err => {
        console.log('获取手机号失败2：', err);
      })
  })
}

// 微信api : 微信登录
function loginFn() {
  return new Promise((resolve, reject) => {
    uni.login({
      success: async (res) => {
        queryOpenIdFn(res.code).then(res => {
          resolve(res)
        })
      },
      fail: (err) => {
        console.log('login fail:', err);
      }
    })
  })
}

export {
  loginFn,
  getPhoneNumberFn
}